const express = require("express");
const fs = require("fs");
const bodyParser = require("body-parser");
const cors = require("cors");
const db = require("./db/db.js");
const app = express();
const { promisify } = require("./utils");
const storeFunc = require("./seller/store.js");
const listingFunc = require("./seller/listing.js");
const toExcel = require("./tools/toExcel.js");

// Parse incoming requests data
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

// Enable Cross-Origin Resource Sharing (CORS)
app.use(cors());

// 获取所有的店铺
app.get("/api/allStore", async (req, res) => {
  fs.readdir("./data", (err, files) => {
    console.log(files);
    if (err) {
      res.json({
        code: "500",
        msg: "店铺不存在，请先创建店铺",
      });
    } else {
      res.json({
        code: "200",
        data: files,
        msg: "执行成功，请等待程序执行",
      });
    }
  });
});

// 执行店铺抓取动作
app.get("/api/crawlerStoreASIN", async (req, res) => {
  const { sellerId } = req.query; // 接收数据
  try {
    storeFunc(sellerId);
    res.json({
      code: "200",
      msg: "执行成功，请等待程序执行",
    });
  } catch (err) {
    console.log(err);
    res.json({
      code: "500",
      msg: "输入有误，请稍后再试",
    });
  }
});

// 抓取店铺全部的ASIN的详情页
app.get("/api/crawlerStoreListing", async (req, res) => {
  const { sellerId } = req.query; // 接收数据

  if (fs.existsSync(`./data/${sellerId}/${sellerId}.txt`)) {
    listingFunc(sellerId);
    res.json({
      code: "200",
      msg: "执行成功，请等待程序执行",
    });
  } else {
    res.json({
      code: "500",
      msg: "店铺数据不存在，请先抓取店铺数据",
    });
  }
});

// 获取店铺全部的产品
app.get("/api/getStoreASIN", async (req, res) => {
  let { sellerId, pageNum = 1 } = req.query; // 接收数据
  try {
    if (fs.existsSync(`./data/${sellerId}/${sellerId}-${pageNum}.txt`)) {
      fs.readFile(
        `./data/${sellerId}/${sellerId}-${pageNum}.txt`,
        "utf-8",
        (err, info) => {
          fs.readdir(`./data/${sellerId}`, "utf-8", (err2, files) => {
            res.json({
              code: "200",
              data: {
                list: !!info ? JSON.parse(info) : [],
                count: files.length - 1,
              },
              msg: "执行成功",
            });
          });
        }
      );
    } else {
      fs.readFile(
        `./data/${sellerId}/${sellerId}.txt`,
        "utf-8",
        (err, info) => {
          console.log(info);
          res.json({
            code: "200",
            data: {
              list: !!info
                ? JSON.parse(info).slice(pageNum - 1 * 20, pageNum * 20)
                : [],
              count: !!info ? Math.ceil(JSON.parse(info).length / 20) : 1,
            },
            msg: "执行成功",
          });
        }
      );
    }
  } catch (err) {
    res.json({
      code: "500",
      msg: "执行失败",
    });
  }
});
// 删除文件夹
app.get("/api/delStore", async (req, res) => {
  let { sellerId } = req.query; // 接收数据
  try {
    fs.rmdirSync(`./data/${sellerId}`, { recursive: true });
    res.json({
      code: "200",
      msg: "操作成功",
    });
  } catch (err) {
    res.json({
      code: "500",
      msg: "执行失败",
    });
  }
});

// 导出数据为excel
app.get("/api/exportData", async (req, res) => {
  let { sellerId } = req.query; // 接收数据
  try {
    fs.readdir(`./data/${sellerId}`, "utf-8", (err, files) => {
      if (Array.isArray(files)) {
        if (fs.existsSync(`./data/${sellerId}/${sellerId}-1.txt`)) {
          let num = files.length - 1;
          let infos = [];
          for (i in num) {
            let info = promisify(fs.readFile)(
              `./data/${sellerId}/${sellerId}-${i + 1}.txt`,
              "utf-8"
            );
            console.log(1)
            infos = infos.concat(JSON.parse(info.replaceAll("][", ",")));
          }
          toExcel(infos, sellerId);
        } else {
          toExcel(`./data/${sellerId}/${sellerId}.txt`, sellerId);
        }
      }
    });
  } catch (err) {
    res.json({
      code: "500",
      msg: "执行失败",
    });
  }
});
// Start the server
const port = process.env.PORT || 3000;

app.listen(port, () => {
  console.log(`Server running on port ${port}`);
});
